package com.jillchen.grpc.server.convertprovidors;

import com.aspose.words.HtmlSaveOptions;
import com.aspose.words.SaveFormat;
import com.jillchen.grpc.server.utils.AbsConverter;
import org.apache.commons.io.FilenameUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;

public class ConvertDocs extends AbsConverter {

    @Override
    public int Convert(String InFile, String OutFile) {

        try {
            long old = System.currentTimeMillis();

            com.aspose.words.Document doc = new com.aspose.words.Document(InFile); //word
            String FileExt = FilenameUtils.getExtension(OutFile).toUpperCase();

            if ("HTML".equals(FileExt) || "MHTML".equals(FileExt)) {
                HtmlSaveOptions options = new HtmlSaveOptions();
                options.setExportFontsAsBase64(true);
                options.setExportImagesAsBase64(true);
                options.setSaveFormat(SaveFormat.fromName(FileExt));
                doc.save(OutFile, options);
            } else {
                doc.save(OutFile, SaveFormat.fromName(FileExt));
            }
            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "s");
            return 0;
        } catch (Exception ex) {
            System.out.println(ex.getMessage() + "\r\n" + Arrays.toString(ex.getStackTrace()));
            return -3;
        }
    }

    @Override
    public int Convert(InputStream inputStream, String InFile, ByteArrayOutputStream outputStream, String OutFile) {
        try {
            long old = System.currentTimeMillis();
            String FileExt = FilenameUtils.getExtension(OutFile).toUpperCase();

            com.aspose.words.Document doc = new com.aspose.words.Document(inputStream); //word


            if ("HTML".equals(FileExt) || "MHTML".equals(FileExt)) {
                HtmlSaveOptions options = new HtmlSaveOptions();
                options.setExportFontsAsBase64(true);
                options.setExportImagesAsBase64(true);
                options.setSaveFormat(SaveFormat.fromName(FileExt));
                doc.save(outputStream, options);
            } else {
                doc.save(outputStream, SaveFormat.fromName(FileExt));
            }
            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "s");
            return 0;

        } catch (
                Exception ex) {
            System.out.println(ex.getMessage() + "\r\n" + Arrays.toString(ex.getStackTrace()));
            return -3;
        }
    }
}
